package com.tarena.lbs.coupon.rpc;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.coupon.api.CouponApi;
import com.tarena.lbs.coupon.api.pojo.param.UserCouponsParam;
import com.tarena.lbs.coupon.pojo.vo.CouponVO;
import com.tarena.lbs.coupon.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@DubboService
public class CouponApiImpl implements CouponApi {

    @Autowired
    private CouponService couponService;

    @Override
    public void receiveCoupon(UserCouponsParam param) throws BusinessException {
        log.info("Dubbo API调用receiveCoupon，参数: {}", param);
        try {
            if (param == null) {
                throw new BusinessException("领取优惠券参数不能为空", "ErrorCode.COUPON_PARAM_NULL");
            }
            if (param.getUserId() == null) {
                throw new BusinessException("用户ID不能为空", "ErrorCode.USER_ID_NULL");
            }
            if (param.getCouponId() == null) {
                throw new BusinessException("优惠券ID不能为空", "ErrorCode.COUPON_ID_NULL");
            }

            // 调用服务层领取优惠券
            couponService.receiveCoupon(param.getUserId(), param.getCouponId());
            log.info("用户领取优惠券成功，userId: {}, couponId: {}", param.getUserId(), param.getCouponId());
        } catch (BusinessException e) {
            log.error("用户领取优惠券失败，param: {}, error: {}", param, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("用户领取优惠券发生异常，param: {}, error: {}", param, e.getMessage(), e);
            throw new BusinessException("领取优惠券失败", "ErrorCode.COUPON_RECEIVE_FAILED");
        }
    }

    // 实现查询优惠券名称的方法
    @Override
    public String getCouponNameById(Integer Id) throws BusinessException {
        log.info("Dubbo API调用getCouponNameById，优惠券ID: {}", Id);
        try {
            if (Id == null) {
                throw new BusinessException("优惠券ID不能为空", "ErrorCode.COUPON_ID_NULL");
            }

            // 直接调用服务层获取优惠券详情
            CouponVO couponVO = couponService.getCouponDetail(Id);
            if (couponVO == null) {
                throw new BusinessException("优惠券不存在", "ErrorCode.COUPON_NOT_EXIST");
            }

            log.info("查询优惠券名称成功，couponId: {}, 名称: {}", Id, couponVO.getCouponName());
            return couponVO.getCouponName();
        } catch (BusinessException e) {
            log.error("查询优惠券名称失败，couponId: {}, error: {}", Id, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("查询优惠券名称发生异常，couponId: {}, error: {}", Id, e.getMessage(), e);
            throw new BusinessException("查询优惠券名称失败", "ErrorCode.COUPON_QUERY_FAILED");
        }
    }
}